package com.psct.wiget;

import java.util.List;

import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.psct.R;
import com.psct.bean.TextData;

public class SearchListView {
	private Context context;
	private PopupWindow popupWindow;
	private ListView listView;
	int with;

	/**
	 * 构造方法
	 * @param context
	 * @param locationView 弹出列表需要显示的位置依据view
	 */
	public SearchListView(Context context,int with) {
		this.context = context;
		this.with=with;
		init();
	}

	private void init() {
		// TODO Auto-generated method stub
		 listView = new ListView(context);
		listView.setAdapter(new SearchAdapter(context));
		popupWindow = new PopupWindow(with,LayoutParams.WRAP_CONTENT);
		//popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(context.getResources().getDrawable(R.color.searchlist_bg));
		popupWindow.setContentView(listView);
	}

	public void show(View view) {
//		popupWindow.showAtLocation(view, Gravity.TOP, 0, 0);
		popupWindow.showAsDropDown(view);
	}
	public void dismiss() {
		popupWindow.dismiss();
	}
    public ListView getListView() {
		return listView;
	}

	public void setListView(ListView listView) {
		this.listView = listView;
	}


	public static class SearchAdapter extends ArrayAdapter<TextData> {
        private final LayoutInflater mInflater;

        public SearchAdapter(Context context) {
            super(context, android.R.layout.simple_list_item_2);
            mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public void setData(List<TextData> data) {
            clear();
            if (data != null) {
                for (TextData appEntry : data) {
                    add(appEntry);
                }
            }
        }

        /**
         * Populate new items in the list.
         */
        @Override public View getView(int position, View convertView, ViewGroup parent) {
            View view;

            if (convertView == null) {
                view = mInflater.inflate(R.layout.list_item_text, parent, false);
            } else {
                view = convertView;
            }
            TextData item = getItem(position);
            ((TextView)view.findViewById(R.id.tv_title)).setText(item.getTitle());
            return view;
        }
    }
}
